package com.caocaog.market.dms.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.caocaog.market.dms.common.DmsCommon;
import com.caocaog.market.dms.dto.*;
import com.caocaog.market.dms.service.DmsService;
import com.caocaog.market.dms.vo.OrderSendVo;
import com.caocaog.market.dms.vo.OrderValuationVo;
import com.caocaog.market.dms.vo.QueryOrderVo;
import com.caocaog.market.toccpt.mapper.MarketOrderMapper;
import com.caocaog.market.toccpt.mapper.OrderBaseInfoMapper;
import com.caocaog.market.toccpt.marketmodel.OrderBaseInfo;
import com.caocaog.market.toccpt.marketmodel.OrderDeliveryInfo;
import com.caocaog.market.toccpt.marketmodel.OrderLineInfo;
import com.caocaog.market.toccpt.marketmodel.ShopInfo;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.RedisUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class DmsServiceImpl implements DmsService {

    @Resource
    private DmsCommon dmsCommon;
    @Resource
    private OrderBaseInfoMapper orderBaseInfoMapper;
    @Resource
    private MarketOrderMapper marketOrderMapper;
    @Resource
    private RedisUtil redisUtil;


    /**
     * 系统自动向曹操跑腿发单
     * @param payNo 支付单号
     * @return
     */
    @Override
    public Result sendOrderToDMS(String payNo) {

        OrderBaseInfo orderBase = orderBaseInfoMapper.findOrderModel(payNo);
            if(Objects.isNull(orderBase)){
                return Result.error("订单暂未支付");
            }

        String orderModel = orderBase.getOrderModel();
        if(StringUtils.isBlank(orderModel)){
            orderBase.setOrderModel("2");
        }
        String shopId=orderBase.getShopId();
        ShopInfo shopInfo = marketOrderMapper.findShopByShopId(shopId);
        OrderDeliveryInfo delivery = marketOrderMapper.findOrderDeliveryByOrderId(orderBase.getOrderId());
        if(orderBase.getOrderModel().equals("2")){
            if(Objects.isNull(orderValuation(orderBase, shopInfo, delivery))){
                return Result.error("获取计价失败");
            }
            OrderSendVo orderSendVo = orderSend(orderBase, shopInfo, delivery);
            if(Objects.isNull(orderSendVo)){
                return Result.error("自动发单失败");
            }

            return Result.OK("发单成功！",orderSendVo);
        }else {
            return Result.error("请手动发单");
        }
    }

    /**
     * 商家端发单计价
     * @param payNo
     * @return
     */
    @Override
    public Result orderValuation(String payNo) {
        OrderBaseInfo orderBase = orderBaseInfoMapper.findOrderModel(payNo);
        if(Objects.isNull(orderBase)){
            return Result.error("订单暂未支付");
        }
        String shopId=orderBase.getShopId();
        ShopInfo shopInfo = marketOrderMapper.findShopByShopId(shopId);
        OrderDeliveryInfo delivery = marketOrderMapper.findOrderDeliveryByOrderId(orderBase.getOrderId());
        OrderValuationVo orderValuationVo = orderValuation(orderBase, shopInfo, delivery);

            return Result.OK("计价成功！",orderValuationVo);
    }

    /**
     * 订单计价业务
     * @param orderBase
     * @return
     */
    OrderValuationVo  orderValuation(OrderBaseInfo orderBase,
                                     ShopInfo shopInfo,
                                     OrderDeliveryInfo delivery){


      OrderValuationDto orderValuationDto = new OrderValuationDto();
      orderValuationDto.setCanhao("");
      orderValuationDto.setDelayTime("");
      orderValuationDto.setFromAddress(shopInfo.getAddressText());
      orderValuationDto.setFromLat(shopInfo.getLat());
      orderValuationDto.setFromLng(shopInfo.getLng());
      orderValuationDto.setFromMobile(orderBase.getMerchantPhone());
      orderValuationDto.setFromName(shopInfo.getName());
      orderValuationDto.setGoodType("meishi");
      orderValuationDto.setGoodsWeight(new BigDecimal(20));
      orderValuationDto.setToAddress(delivery.getDeliveryAddress());
      orderValuationDto.setToLat(delivery.getDeliveryLat());
      orderValuationDto.setToLng(delivery.getDeliveryLng());
      orderValuationDto.setToMobile(delivery.getDeliveryMobile());
      orderValuationDto.setToName(delivery.getDeliveryName());
      orderValuationDto.setShopId(shopInfo.getId());

      OrderValuationVo orderValuationVo = dmsCommon.orderValuation(orderValuationDto);
      if(Objects.isNull(orderValuationVo)){
          return null;
        }
        return orderValuationVo;
    }

    /**
     * 订单发单业务
     * @param orderBase
     * @param shopInfo
     * @param delivery
     * @return
     */
 OrderSendVo orderSend(OrderBaseInfo orderBase,
              ShopInfo shopInfo,
              OrderDeliveryInfo delivery){

        OrderSendDto sendDto=new OrderSendDto();
        sendDto.setCanhao("");
        sendDto.setDelayTime("");
        sendDto.setIsDelay(0);
        sendDto.setFromAddress(shopInfo.getAddressText());
        sendDto.setFromLat(shopInfo.getLat());
        sendDto.setFromLng(shopInfo.getLng());
        sendDto.setFromMobile(shopInfo.getServicePhone());
        sendDto.setFromName(shopInfo.getName());
        sendDto.setGoodType("meishi");
        sendDto.setGoodsList(selectOrderLine(orderBase.getOrderId()));
        sendDto.setGoodsWeight(new BigDecimal(20));
        sendDto.setToAddress(delivery.getDeliveryAddress());
        sendDto.setToLat(delivery.getDeliveryLat());
        sendDto.setToLng(delivery.getDeliveryLng());
        sendDto.setToMobile(delivery.getDeliveryMobile());
        sendDto.setToName(delivery.getDeliveryName());
        sendDto.setOriginOrderNo(orderBase.getOrderNo());
        sendDto.setShopId(shopInfo.getId());
        sendDto.setOrderSource("125");

     String key="DmsOrder:"+orderBase.getOrderNo();
         Object o = redisUtil.get(key);
         if(Objects.nonNull(o)){
                return null;
         }
        OrderSendVo orderSendVo = dmsCommon.orderSend(sendDto);

        redisUtil.set(key,orderSendVo.getPtOrderNo(), 60*60*24);

            if(Objects.isNull(orderSendVo)){
                return null;
            }

        return orderSendVo;
    }

    /**
     * 商家端手动发单
     * @param payNo
     * @return
     */
    @Override
    public Result opSendOrderToDMS(String payNo) {
        OrderBaseInfo orderBase = orderBaseInfoMapper.findOrderModel(payNo);
        if(Objects.isNull(orderBase)){
            return Result.error("订单暂未支付");
        }

        String orderModel = orderBase.getOrderModel();
        if(StringUtils.isBlank(orderModel)){
            orderBase.setOrderModel("1");
        }
        String shopId=orderBase.getShopId();
        ShopInfo shopInfo = marketOrderMapper.findShopByShopId(shopId);
        OrderDeliveryInfo delivery = marketOrderMapper.findOrderDeliveryByOrderId(orderBase.getOrderId());
        if(orderBase.getOrderModel().equals("1")){
            if(Objects.isNull(orderValuation(orderBase, shopInfo, delivery))){
                return Result.error("获取计价失败");
            }
            OrderSendVo orderSendVo = orderSend(orderBase, shopInfo, delivery);
            if(Objects.isNull(orderSendVo)){
                return Result.error("自动发单失败");
            }
            return Result.OK("发单成功！",orderSendVo);
        }
        return Result.error("发单失败:检查店铺发单设置");
    }

    /**
     * 商家端绑定用户
     * @param bindUserDto
     * @return
     */
    @Override
    public Result<Boolean> bindUser(BindUserDto bindUserDto) {
        Result result=new Result();
        if(Objects.isNull(bindUserDto)){
            return result.error500("绑定信息有误，请检查！");
        }
        if(dmsCommon.bindUser(bindUserDto)){
            return result.success("绑定成功！");
        }else {
            return result.error500("绑定曹操跑腿失败！");
        }
    }

    /**
     * 商家端解绑用户
     * @param bindUserDto
     * @return
     */
    @Override
    public Result<Boolean> unBindUser(BindUserDto bindUserDto) {
        String redisKey ="caocaoToken:"+bindUserDto.getShopId();
        Object o = redisUtil.get(redisKey);
       if(Objects.isNull(o)){
           return Result.OK("解绑失败", false);
       }
        redisUtil.del(redisKey);
        return Result.OK("解绑成功",true);
    }

    @Override
    public Result<BigDecimal> getBalance(String shopId) {
        Result result = new Result();
        if(Objects.isNull(shopId)){
            return result.error500("店铺信息错误");
        }
        BigDecimal balance = dmsCommon.getBalance(shopId);
        if(Objects.isNull(balance)){
            return result.error500("曹操跑腿余额查下失败");
        }
            return Result.OK(balance);
    }
  List<GoodsDto> selectOrderLine(String orderId){

      List<OrderLineInfo> list = marketOrderMapper.findOrderLineByOrderId(orderId);
      if(list!=null && list.size()>0){
          List<GoodsDto> goodsList=new ArrayList<>();
           for (OrderLineInfo info:list){
               GoodsDto goodsDto=new GoodsDto();
               goodsDto.setName(info.getLineGoodsName());
               goodsDto.setTotalCount(Integer.parseInt(info.getLineQuantity()));
               goodsDto.setTotalPrice(new BigDecimal(info.getLinePrice()));
               goodsList.add(goodsDto);
           }
           return goodsList;
      }
   return Collections.emptyList();
  }

  @Override
  public Result<QueryOrderVo> orderQuery(QueryOrderDto queryDto){

        String key="DmsOrder:"+queryDto.getOrderNo();
        String ptOrderNo= String.valueOf(redisUtil.get(key));
        Result result = new Result();
        if(Objects.isNull(ptOrderNo)){
            return result.OK("未查询到跑腿订单",null);
        }

        QueryOrderDto queryOrderDto= new QueryOrderDto();
        queryOrderDto.setOrderNo(ptOrderNo);
        queryOrderDto.setShopId(queryDto.getShopId());

        QueryOrderVo vo = dmsCommon.orderQuery(queryOrderDto);
        return result.OK("查询成功",vo);

    }

    @Override
    public Result<Boolean> orderCancel(QueryOrderDto queryDto){

        String key="DmsOrder:"+queryDto.getOrderNo();
        String ptOrderNo= (String) redisUtil.get(key);
        Result result = new Result();
        if(Objects.isNull(ptOrderNo)){
            return result.OK("跑腿未发单",true);
        }

        QueryOrderDto queryOrderDto= new QueryOrderDto();
        queryOrderDto.setOrderNo(ptOrderNo);
        queryOrderDto.setShopId(queryDto.getShopId());
       if(dmsCommon.orderCancel(queryOrderDto)){
           return result.OK("取消成功",true);
       }
        return result.error500("取消失败");
    }
}
